package com.smartrobot.smartrobot.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;

import com.application.SmartRobotApplication;
import com.easemob.EMCallBack;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMContactManager;
import com.easemob.chat.EMGroupManager;
import com.easemob.util.EMLog;
import com.huanxinapi.activity.BaseActivity;
import com.huanxinapi.activity.UserDao;
import com.smartrobot.smartrobot.Common.CommonFunc;
import com.smartrobot.smartrobot.R;
import com.smartrobot.smartrobot.logToSdCard.LogToSd;
import com.smartrobot.smartrobot.util.HttpUtil;
import com.smartrobot.smartrobot.util.User;
import com.smartrobot.smartrobot.view.ToastCustom;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by Administrator on 2015/1/23.
 */
public class SplashActivity extends BaseActivity {

    private final int LONGIN_HUANXIN_OK = 1111;
    private final int LONGIN_HUANXIN_FAILD = 1112;
    private SplashHandler handler;
    private User user;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.page_splash);
        SmartRobotApplication.getInstance().logout(null);

                if(User.getInstance().getId().equals("未填写")){
                    if(User.getUserInfo(getApplicationContext())){
                        user = User.getInstance();
                        if(user.getIsLogin()){//曾经登录过直接跳到splash界面
                        }else{//没有登录过要跳到登录界面
                            toLogin();
                        }
                    }else{
                        toLogin();
                    }


                }else{

                    user = User.getInstance();

                    if(user.getIsLogin()){//曾经登录过直接跳到splash界面

                    }else{//没有登录过要跳到登录界面
                        toLogin();
                    }

                }


    }


    @Override
    protected void onResume() {
        super.onResume();

        new Handler().postAtTime(new Runnable() {
            @Override
            public void run() {
                LogToSd.log_init();
                initView();
            }
        },1000);


    }

    void initView(){

        handler = new SplashHandler();
        HttpUtil.init(getApplicationContext());
        HttpUtil.reLogin(getApplicationContext(),handler);
    }


    class SplashHandler extends Handler{

        @Override
        public void dispatchMessage(Message msg) {

            switch (msg.what){

            case HttpUtil.LOGIN_SUCCESS:

//                socketUtil.initSocket_2(getApplicationContext());

                final String  account = User.getInstance().getPhone();
                final String  password = CommonFunc.stringToMD5(account);
                // 调用sdk登陆方法登陆聊天服务器
                EMChatManager.getInstance().login(account, password, new EMCallBack() {

                    @Override
                    public void onSuccess() {

                        // 登陆成功，保存用户名密码
                        SmartRobotApplication.getInstance().setUserName(account);
                        SmartRobotApplication.getInstance().setPassword(password);
                        try {
                            // ** 第一次登录或者之前logout后再登录，加载所有本地群和回话
                            // ** manually load all local groups and
                            // conversations in case we are auto login
                            EMGroupManager.getInstance().loadAllGroups();
                            EMChatManager.getInstance().loadAllConversations();

                            // demo中简单的处理成每次登陆都去获取好友username，开发者自己根据情况而定
                            List<String> usernames = EMContactManager.getInstance().getContactUserNames();
                            EMLog.d("roster", "contacts size: " + usernames.size());
                            Map<String,  com.huanxinapi.activity.User> userlist = new HashMap<String,  com.huanxinapi.activity.User>();
                            for (String username : usernames) {
                                com.huanxinapi.activity.User user = new com.huanxinapi.activity.User();
                                user.setUsername(username);
//                                setUserHearder(username, user);
                                userlist.put(username, user);
                            }
                            // 存入内存
                            SmartRobotApplication.getInstance().setContactList(userlist);
                            // 存入db
                            UserDao dao = new UserDao(SplashActivity.this);
                            List< com.huanxinapi.activity.User> users = new ArrayList< com.huanxinapi.activity.User>(userlist.values());
                            dao.saveContactList(users);

                            // 获取群聊列表(群聊里只有groupid和groupname等简单信息，不包含members),sdk会把群组存入到内存和db中
//                            EMGroupManager.getInstance().getGroupsFromServer();
                        } catch (Exception e) {
                            e.printStackTrace();
                            //取好友或者群聊失败，不让进入主页面，也可以不管这个exception继续进到主页面 直接进入主机卖弄这里没有操作
//                            return;
                        }
                        //更新当前用户的nickname 此方法的作用是在ios离线推送时能够显示用户nick
                        boolean updatenick = EMChatManager.getInstance().updateCurrentUserNick(SmartRobotApplication.currentUserNick.trim());
                        if (!updatenick) {
                            Log.e("LoginActivity", "update current user nick fail");
                        }


                        Message msg = new Message();
                        msg.what = LONGIN_HUANXIN_OK;
                        handler.sendMessage(msg);


                    }

                    @Override
                    public void onProgress(int progress, String status) {
                    }

                    @Override
                    public void onError(final int code, final String message) {

                        Message msg = new Message();
                        msg.what = LONGIN_HUANXIN_FAILD;
                        handler.sendMessage(msg);
                        LogToSd.debug("环信登录失败："+message.toString());
                    }
                });


                break;

            case HttpUtil.LOGIN_FAILD:

                ToastCustom.showToast(getApplicationContext(), "登录失败,连接服务器错误！");
                if(msg.obj != null){
                    if(msg.obj.equals("106")) {
                        ToastCustom.showToast(SplashActivity.this, "账号或密码错误!");
                        toLogin();
                    }
                    else
                        ToastCustom.showToast(SplashActivity.this, "登陆服务器失败，请稍后再试");
                }
                else
                    ToastCustom.showToast(SplashActivity.this, "登陆服务器失败，请稍后再试");
                SplashActivity.this.finish();

                break;

            case LONGIN_HUANXIN_OK:

                User.getInstance().setIsLogin(true);//这就意味着可以跳过登录界面
                User.saveUserInfo(getApplicationContext());
                startActivity(new Intent(SplashActivity.this, MainActivity.class));
                SplashActivity.this.finish();

                break;

            case LONGIN_HUANXIN_FAILD:

                ToastCustom.showToast(getApplicationContext(), "登录失败，请稍后再试！" );
                SplashActivity.this.finish();

                    break;


            }



        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) { //成为后台程序
            moveTaskToBack(true);
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }


    void toLogin(){

        Intent intent1 = new Intent();
        intent1.setClass(this,LoginActivity.class);
        startActivity(intent1);
        this.finish();

    }


}
